/**
 * Created by Administrator on 2016/6/24.
 */
package
{
	import flash.desktop.Clipboard;
	import flash.desktop.ClipboardFormats;
	import flash.desktop.NativeDragManager;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.NativeDragEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;

	import org.flexlite.domCore.Injector;
	import org.flexlite.domUI.components.Alert;
	import org.flexlite.domUI.components.Button;
	import org.flexlite.domUI.components.Group;
	import org.flexlite.domUI.components.Label;
	import org.flexlite.domUI.components.Rect;
	import org.flexlite.domUI.components.TextInput;
	import org.flexlite.domUI.core.Theme;
	import org.flexlite.domUI.layouts.HorizontalLayout;
	import org.flexlite.domUI.layouts.VerticalLayout;
	import org.flexlite.domUI.managers.SystemManager;

	import themeEx.VectorThemeEx;

	public class AppContainer extends SystemManager
	{
		private var _browserBtn:Button;
		private var _packageBtn:Button;

		private var _fileList:Array;

		//打包文件的后缀名
		private var _packageExtension:String = "cfg";
		private var _projectInput:TextInput;

		public function AppContainer()
		{
			Injector.mapClass(Theme, VectorThemeEx);//这里为了方便调试，一次性注入所有组件的默认皮肤。正式项目中不需要默认皮肤,应当自定义主题。
		}

		override protected function createChildren():void
		{
			super.createChildren();

			var rect:Rect = new Rect();
			rect.percentWidth = 100;
			rect.percentHeight = 100;
			rect.fillAlpha = 0;
			rect.fillColor = 0;
			this.addElement(rect);
			rect.mouseEnabled = false;
			rect.mouseChildren = false;


			var topGroup:Group = new Group();
			topGroup.layout = new HorizontalLayout();
			addElement(topGroup);
			topGroup.left = 5;
			topGroup.top = 5;

			var tipLabel:Label = new Label();
			tipLabel.text = "请输入打包的文件扩展名";
			topGroup.addElement(tipLabel);

			var input:TextInput = new TextInput();
			topGroup.addElement(input);
			input.width = 150;
			input.text = _packageExtension;

			input.addEventListener(Event.CHANGE, function ():void
			{
				var extension:String = input.text;
				if (extension != null)
				{
					_packageExtension = extension;
				}
			});


			var secondRow:Group = new Group();
			secondRow.layout = new HorizontalLayout();
			this.addElement(secondRow);
			secondRow.left = 5;
			secondRow.top = 30;

			var projectPath:Label = new Label();
			projectPath.text = "打包路径";
			secondRow.addElement(projectPath);


			_projectInput = new TextInput();
			_projectInput.width = 300;
			secondRow.addElement(_projectInput);
			_projectInput.enabled = false;


			var container:Group = new Group();
			var containerLayout:VerticalLayout = new VerticalLayout();
			containerLayout.gap = 10;
			container.layout = containerLayout;
			this.addElement(container);
			container.top = 5;
			container.right = 5;

			_browserBtn = new Button();
			_browserBtn.width = 70;
			_browserBtn.height = 40;
			_browserBtn.label = "浏览";
			container.addElement(_browserBtn);


			_packageBtn = new Button();
			_packageBtn.width = 70;
			_packageBtn.height = 40;
			_packageBtn.label = "打包";
			container.addElement(_packageBtn);

			container.addEventListener(MouseEvent.CLICK, onClickHandler);
			receiveDrag();
		}

		private function onClickHandler(event:MouseEvent):void
		{
			var obj:Object = event.target;
			if (obj == _browserBtn)
			{
				browserHandler();
			} else if (obj == _packageBtn)
			{
				packageHandler();
			}
		}

		private function packageHandler():void
		{
			if (isSetFilePath())
			{
				this.packageXml();
			} else
			{
				Alert.show("请检查配置是否正确？");
			}
		}

		private var file:File = new File();

		private function browserHandler():void
		{
			file.browseForDirectory("浏览");
			file.addEventListener(Event.SELECT, onSelect);
		}

		private function onSelect(event:Event):void
		{
			file.removeEventListener(Event.SELECT, onSelect);
			if (_projectInput)
			{
				_projectInput.text = file.nativePath;
			}
		}

		private function isSetFilePath():Boolean
		{
			if (_projectInput)
			{
				var path:String = _projectInput.text;

				var fileList:Array;
				var selectFile:File = File.desktopDirectory.resolvePath(path);
				if (selectFile.isDirectory)
				{
					fileList = selectFile.getDirectoryListing();
				} else
				{
					fileList = selectFile.parent.getDirectoryListing();
				}

				if (fileList && fileList.length > 0)
				{
					fileList = fileList.filter(function (element:File, index:int, arr:Array):Boolean
					{
						if (element.extension != _packageExtension)
						{
							return false;
						}
						return true;
					});
				}

				if (fileList && fileList.length > 0)
				{
					_fileList = fileList;
					return true;
				}
			}
			return false;
		}

		private function receiveDrag():void
		{
			stage.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER, dragEnterHandler);
			stage.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP, dragDropHandler);
			stage.addEventListener(NativeDragEvent.NATIVE_DRAG_EXIT, dragExitHandler);
		}

		private function dragExitHandler(event:NativeDragEvent):void
		{
			trace("exit");
		}

		private function dragDropHandler(event:NativeDragEvent):void
		{
			trace("drop");
			var clip:Clipboard = event.clipboard;
			if (clip.hasFormat(ClipboardFormats.FILE_LIST_FORMAT))
			{
				var arr:Array = clip.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
				var file:File = arr[0] as File;
				var fileList:Array;
				if (file.isDirectory)
				{
					fileList = file.getDirectoryListing();
					if (_projectInput)
					{
						_projectInput.text = file.nativePath;
					}
				} else
				{
					fileList = file.parent.getDirectoryListing();
					if (_projectInput)
					{
						_projectInput.text = file.parent.nativePath;
					}
				}
			}
		}

		private function packageXml():void
		{
			if (_fileList == null || _fileList.length <= 0)
			{
				return;
			}
			var fileList:Array = _fileList;
			var byteArray:ByteArray = new ByteArray();
			for each(var f:File in fileList)
			{
				var st:FileStream = new FileStream();
				st.open(f, FileMode.READ);
				var xmlData:ByteArray = new ByteArray();
				st.readBytes(xmlData);

				var byte:ByteArray = new ByteArray();
				byte.writeUTF(f.name);  //名字
				byte.writeInt(xmlData.length);//长度
				byte.writeBytes(xmlData, 0, xmlData.length);//内容
				byteArray.writeBytes(byte, 0, byte.length);
			}
			byteArray.position = 0;
			byteArray.compress();

			var fileStream:FileStream = new FileStream();
			var path:String = (fileList[0].parent).nativePath;
			var newFile:File = File.desktopDirectory.resolvePath(path + File.separator + "data.bin");
			fileStream.open(newFile, FileMode.WRITE);
			fileStream.position = 0;
			fileStream.writeBytes(byteArray, 0, byteArray.length);
			fileStream.close();
		}

		private function dragEnterHandler(event:NativeDragEvent):void
		{
			var clipBoard:Clipboard = event.clipboard;
			if (clipBoard.hasFormat(ClipboardFormats.FILE_LIST_FORMAT))
			{
				NativeDragManager.acceptDragDrop(stage);
			}
		}
	}
}
